/*FdWCknFuTawwFv7yuXti14UGtWEeBwD1UZmZ/3R9DQDBsYOzASSE7cOvrNY6AeQC*/
/*
 * @Descripttion:
 * @version:
 * @Author: Chendch
 * @Date: 2018-10-10 17:36:07
 * @LastEditors: Chendch
 * @LastEditTime: 2021-09-18 13:34:48
 */
import { pageTo, metaCache, viewModel, gzip} from "nc-lightapp-front";
import { isObject } from "./typeCheck";
const {getMetaCache} = metaCache;
const { getGlobalStorage } = viewModel;
const Gzip = gzip;
let gziptools = new Gzip();

/**
 * @desc 判断字符串包含
 * @param  {string} 原始字符串
 * @param {substr} 子字符串
 * @param {isIgnoreCase} 忽略大小写
 * @return {Booelan}
 */
export const strContains = (string, substr, isIgnoreCase) => {
	if(isIgnoreCase) {
        string = string.toLowerCase();
        substr = substr.toLowerCase();
    }
    let startChar = substr.substring(0,1);
    const strLen = substr.length;
    for(let j=0; j< string.length-strLen+1; j++) {
        if(string.charAt(j) == startChar) {
            if(string.substring(j, j+strLen == substr)) {
                return true;
            }
        }
    }
    return false;
}

/**
 * 利用input/textarea复制文本至剪切板实现复制
 * **/
export const copyToClipboard = (elem) => {
    var targetId = "_hiddenCopyText_";
    var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
    var origSelectionStart, origSelectionEnd;
    if (isInput) {
      target = elem;
      origSelectionStart = elem.selectionStart;
      origSelectionEnd = elem.selectionEnd;
    } else {
      target = document.getElementById(targetId);
      if (!target) {
        var target = document.createElement("textarea");
        target.style.position = "absolute";
        target.style.left = "-9999px";
        target.style.top = "0";
        target.id = targetId;
        document.body.appendChild(target);
      }
      target.textContent = elem//elem.textContent;
    }
    // select the content
    var currentFocus = document.activeElement;
    target.focus();
    target.setSelectionRange(0, target.value.length);

    // copy the selection
    var succeed;
    try {
      succeed = document.execCommand("copy");
      //successPromptsuccessPrompt('复制成功', 'middle', 1000)
    } catch(e) {
      succeed = false;
      //errorPrompt('请手动复制', 'middle', 1000)
    }
    // restore original focus
    if (currentFocus && typeof currentFocus.focus === "function") {
      currentFocus.focus();
    }

    if (isInput) {
      // restore prior selection
      elem.setSelectionRange(origSelectionStart, origSelectionEnd);
    } else {
      // clear temporary content
      target.textContent = "";
    }
    return succeed;
  }


 /**
 * 获取字符在指定字符串中存在的个数
 * **/
export const getStrNum = (str, papStr) => {
  if(!str || !papStr) return false;
  const regex = new RegExp(papStr, 'g'); // 使用g表示整个字符串都要匹配
  const result = str.match(regex);
  const count = !result ? 0 : result.length;
  return count;
}

/*
 * @method   if条件下为false   除去NaN、0、-0、false   剩余undefined、null、""
 * @params
 *     condition     {any}
 * @return   {boolean}       返回ture/false
 * @demo     isWrong('')    因为后台返回数据不规范
 */
export function isWrong(param) {
  return typeof param === 'undefined' || param === null || param === '';
}


/*
 * @method   检测是否是个数字(包括数字字符串  但是不包括 344. 这种)
 * @params
 *     val        {Any}      元数据
 * @return   {Boolean}       true/false
 * @demo     isRealNum(234533)
 */
export function isRealNum(val) {
  var patrn = /^(-)?\d+(\.\d+)?$/;
  if (patrn.exec(val) == null || val === '') {
      return false;
  } else {
      return true;
  }
}

/*
 * @method   把B字节的size转化为特定容量
 * @params
 *     bytes      {Number}      元数据
 *     fixed      {Number}      小数位数  默认为2位
 * @return   {String}           返回相应的数量
 * @demo     bytesToSize(234533, 2)
 */
export function bytesToSize(bytes, fixed, unit) {
  fixed = fixed || 2;
  if (bytes == 0 || typeof bytes === 'undefined' || !isRealNum(bytes))
      return fixed > 0 ? `0.${Array(fixed + 1).join('0')}B` : '0B';
  var k = 1024,
      sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
      i = isWrong(unit) ? Math.floor(Math.log(bytes) / Math.log(k)) : unit;
  return (bytes / Math.pow(k, i)).toFixed(fixed) + sizes[i];
}

function isJSON(str) {
  if (typeof str == 'string') {
    try {
      let obj=JSON.parse(str);
      if(typeof obj == 'object' && obj ){
        return true;
      }else{
        return false;
      }

    } catch(e) {
      console.log('error：'+str+'!!!'+e);
      return false;
    }
  }else if(Object.prototype.toString.call(str).slice(8, -1).toLowerCase() == "object") {
    return true;
  }
  return false;
}

/*
 * @method   判断指定区域内的按钮是否有权限
 * @params
 *     moduleId      {String}   按钮区域快
 *     btnKey      {String}     自定义按钮key
 * @return   {Boolean}
 * @demo     checkBtnAuthInModule("btn-group", "sum")
 */
export function checkBtnAuthInModule(moduleId, btnKey, props = {}) {
  let status = false,
    btnList = [], buttonData = null;
  if((!window.moduleId) || (Array.isArray(window.moduleId) && !window.moduleId.length)) {
    let appcode = props.getUrlParam ? props.getUrlParam("appcode") : pageTo.getSearchParam("c"),
      pagecode = props.getUrlParam ? props.getUrlParam("pagecode") : pageTo.getSearchParam("p");
    // console.log("666--", props, appcode, pagecode)
    if(props.childAppcode && props.childPagecode) {//iframe二次嵌套模板取值错误
      appcode = props.childAppcode;
      pagecode = props.childPagecode;
    }
    if(!!props.noControlPermission) {//不需要控制权限
      return true;
    }
    if(!appcode || !pagecode) return status;
    let tempalteCache = getMetaCache(appcode, pagecode);
    // console.log("tempalteCache---", {tempalteCache})
    try{
      if(getGlobalStorage('localStorage', 'gzip') === '1' && !isJSON(tempalteCache)) {
        tempalteCache = gziptools.unzip(tempalteCache);
      }
    }catch(err) {
      console.log("非云原生，未开启local加密")
      tempalteCache = tempalteCache;
    }

    if(!tempalteCache) return status;
    buttonData = typeof(tempalteCache) === "string" ? JSON.parse(tempalteCache).button : tempalteCache.button;
    //特殊处理下button.button取值
    if(Object.prototype.toString.call(buttonData).slice(8, -1).toLowerCase() == "object" && Object.keys(buttonData).length) {
      buttonData = buttonData.button;
    }
    if(!buttonData || !buttonData.length) return status;
    btnList = buttonData.filter( item => {
      return item.area === moduleId
    }).map( list => {
      return list.key;
    });
    // console.log("btnList---", {btnList})
    window.moduleId = btnList;
  }else {
    btnList = window.moduleId;
  }
  return btnList.includes(btnKey);
}
/*FdWCknFuTawwFv7yuXti14UGtWEeBwD1UZmZ/3R9DQDBsYOzASSE7cOvrNY6AeQC*/
